package com.zua.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.zua.entity.*;
import com.zua.service.CatelogService;
import com.zua.service.GoodService;
import com.zua.service.OrderService;
import com.zua.util.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
@CrossOrigin(origins = "*",allowCredentials = "true")
@RestController
@RequestMapping("Good")
public class GoodController {
    @Autowired
    private GoodService goodService;
    @Autowired
    private CatelogService catelogService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private OrderService orderService;
    private ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 管理员查询所有商品
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("goods")
    public Map  showAll(@RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "5")Integer pageSize){
        List<Good> list = goodService.selectAll(pageNum, pageSize);
        for (Good g:list
             ) {
            g.setImgUrl("http://localhost:8989/ZuaMarket/good/upload/"+g.getImgUrl());
            System.err.println(g);
        }
        PageInfo<Good> pageInfo = new PageInfo<>(list,10);
        long total = pageInfo.getTotal();
        int[] pages = pageInfo.getNavigatepageNums();
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("pages",pages);
        map.put("total",total);
        return map;
    }
    /**
     * 获取最新发布
     * @return
     */
    @GetMapping("/main/newGoods")
    public Map userShowNewGoods(){
        HashMap<String, Object> map = new HashMap<>();
        List<Good> goods = goodService.userShowNewGoods();
        for (Good good : goods) {
            good.setImgUrl("../../good/upload/"+good.getImgUrl());
        }
        map.put("status","success");
        map.put("goods",goods);
        return map;
    }
    /**
     * 根据分类编号查询该分类下查询所有物品   以及查询当前分类
     * @param catelogId
     * @return
     */
    @GetMapping("/main/catelogGoods/{id}")
    public Map showCatelogGoods(@PathVariable("id")Integer catelogId){
        HashMap<String, Object> map = new HashMap<>();
        List<Good> goods = goodService.selectByCatelog(catelogId);
        Catelog catelog = catelogService.selectByid(catelogId);
        for (Good good : goods) {
            good.setImgUrl("../../good/upload/"+good.getImgUrl());
        }
        map.put("status","success");
        map.put("goods",goods);
        map.put("catelog",catelog);
        return map;
    }
    /**
     * 根据输入关键字进行模糊查询
     * @param entry
     * @return
     */
    @GetMapping("/main/searchGoods/{entry}")
    public Map showSearchGoods(@PathVariable("entry")String entry){
        HashMap<String, Object> map = new HashMap<>();
        List<Good> goods = goodService.selectByEntry(entry);
        for (Good good : goods) {
            good.setImgUrl("../../good/upload/"+good.getImgUrl());
        }
        map.put("goods",goods);
        return map;
    }
    /**
     * 根据id将物品收藏
     * @param goodId
     * @return
     */
    @GetMapping("/user/collectGood/{goodId}")
    public Map CollectGood(@PathVariable("goodId")Integer goodId){
        //构建map  根据id查询想要收藏的物品  获取连接redis对象jedis  获取session和存入的user
        HashMap<String, Object> map = new HashMap<>();
        Good good = goodService.selectById(goodId);
        good.setImgUrl("/ZuaMarket/good/upload/"+good.getImgUrl());
        System.out.println("good = " + good);
        CollectGoods collectGoods = new CollectGoods();
        Jedis jedis = JedisUtils.getJedis();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //如果user是空的  就说明没有用户登陆  直接返回
        if(user==null){
            map.put("status","noLogin");
            return map;
        }
        //card+userid 就是存入redis的键
        String key = "Cart"+user.getId();
        //获取对应用户的cart
        String cart = jedis.get(key);
        if(cart==null){
            //如果获取到的是空 说明该用户没有添加过收藏  新建一个收藏对象  将物品加入收藏对象中
            HashSet<Good> collectSet = new HashSet<>();
            collectSet.add(good);
            collectGoods.setCollectSet(collectSet);
            map.put("status","success");
        }else{
            //如果有  将收藏json串转换为collectGoods对象
            try {
                collectGoods = objectMapper.readValue(cart,CollectGoods.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取set集合  添加物品  set集合自动去重
            HashSet<Good> collectSet = collectGoods.getCollectSet();
            collectSet.add(good);
            collectGoods.setCollectSet(collectSet);
            map.put("status","success");
        }
        //将新的collectGoods对象转换为字符串  存入jedis中
        try {
            String value = objectMapper.writeValueAsString(collectGoods);
            jedis.set(key,value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            map.put("status","failed");
        }
        return map;
    }
    /**
     * 根据物品id从session中获取用户生成订单
     * @param goodId
     * @return
     */
    @GetMapping("/user/newOrder/{goodId}")
    public Map getNewOrder(@PathVariable("goodId")int goodId){
        HashMap<String, Object> map = new HashMap<>();
        User user = (User)request.getSession().getAttribute("user");
        if(user==null){
            map.put("status","noLogin");
            return map;
        }
        Good good = goodService.selectById(goodId);
        good.setImgUrl("/ZuaMarket/good/upload/"+good.getImgUrl());
        Order newOrder = new Order(1,goodId,good.getName(), user.getId(), good.getPrice(), null,0);
        orderService.insertOrder(newOrder);
        map.put("status","success");
        return map;
    }
    /**
     * 根据前端页面传入的信息新的物品信息传入数据库中
     * @param good
     * @return
     */
    @PutMapping("/user/addGood")
    public Map addGood(@RequestBody Good good){
        HashMap<String, Object> map = new HashMap<>();
        System.err.println("goodsaasasa = " + good);
        if(good.getUserId()==0){
            User user = (User)request.getSession().getAttribute("user");
            good.setUserId(user.getId());
        }
        goodService.insertGood(good);
        map.put("state","success");
        return map;
    }
    /**
     * 根据id删除物品
     * @param id
     * @return
     */
    @DeleteMapping("/good/{id}")
    public Map deleteGood(@PathVariable("id") Integer id){
        HashMap<String, Object> map = new HashMap<>();
        try {
            goodService.deleteById(id);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 修改商品信息
     * @param good
     * @return
     */
    @PutMapping("/changeGood")
    public Map changeGood(@RequestBody Good good){
        HashMap<String, Object> map = new HashMap<>();
        try {
            goodService.updateGood(good);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
}
